package com.tdogg.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.tdogg.entity.Cart;
import com.tdogg.entity.Users;
import com.tdogg.service.ICartService;
import com.tdogg.service.IUserService;
import com.tdogg.util.MD5Utils;
import com.tdogg.util.RedisUtil;
import com.tdogg.util.UUIDUtil;
import com.zhenzi.sms.ZhenziSmsClient;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

@Controller
@RequestMapping("/user")
public class UserController {
	private static final String String = null;
	@Autowired
	private IUserService userService;
	
	@RequestMapping("login")
	@ResponseBody
	public String login(Users us,HttpServletRequest request){
		if(us.getUserPhone()==null) {
			us.setUserPhone(us.getUserName());
		}
		JSONObject json = (JSONObject)request.getSession().getAttribute("verifyCode");
        if(us.getUserPass().equals("")){//对比发出去的验证码和传回来的验证码
        	if(!json.getString("mobile").equals(us.getUserPhone())){
            	return "pfail";
    		}else if(!json.getString("verifyCode").equals(us.getVerifyCode())){
            	return "vfail";
            }else if((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 5){
            	return "tfail";
            }else {
            	Users user = userService.login(us.getUserName(), "",true);
            	if(user!=null){
        			HttpSession session = request.getSession();
        			session.setAttribute("user", user);
        			session.removeAttribute("verifyCode");
        			return "success";
        		}
            }
		}else {
			Users user = userService.login(us.getUserName(), us.getUserPass(),false);
			if(user!=null){
				HttpSession session = request.getSession();
				session.setAttribute("user", user);
				return "success";
			}
			return "fail";
		}
        return "fail";
	}
	@RequestMapping("logout")
	public String logout(HttpServletRequest request){
		HttpSession session = request.getSession();
		session.removeAttribute("user");
		return "index";
	}
	
	@RequestMapping("amendinfo")
	public String preModifyInfo(HttpServletRequest request,Model model){
		HttpSession session = request.getSession();
		Users user = (Users) session.getAttribute("user");
		model.addAttribute("user", user);
		return "userview/amend_info";
	}
	@RequestMapping(value="upload",method={RequestMethod.POST})
	@ResponseBody
	public JSONObject uploadHeaderPic(@PathVariable(value="file")MultipartFile file,HttpServletRequest request){
		String str = file.getOriginalFilename();
		String name=UUIDUtil.getUUID()+str.substring(str.lastIndexOf("."));
		String path=request.getServletContext().getRealPath("/upload")+"/"+name;
		try {
			file.transferTo(new File(path));
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		JSONObject obj=new JSONObject();
		obj.put("userImg", name);
		return obj;
	}
	@RequestMapping("updateUserInfo")
	@ResponseBody
	public String updateUserInfo(Users user,Model model,HttpServletRequest request){
		Integer rs = userService.updateUserInfo(user);
		if(rs>0){
			Users u = userService.findUserById(user.getUserId());
			HttpSession session = request.getSession();
			session.setAttribute("user", u);
			return "success";
		}
		return "fail";
	}
	@RequestMapping("modifyUserPass")
	@ResponseBody
	public String modifyUserPass(String verifyCode,String newPass,String rePass,HttpServletRequest request){
		HttpSession session = request.getSession();
		Users user = (Users) session.getAttribute("user");
		JSONObject json = (JSONObject)session.getAttribute("verifyCode");
		if(((System.currentTimeMillis() - json.getLong("createTime")) <= 1000 * 60 * 5) && (json.getString("verifyCode").equals(verifyCode)) && newPass.equals(rePass)){
			user.setUserSalt(RandomStringUtils.randomAscii(12));
			user.setUserPass(MD5Utils.passToMD5(newPass+user.getUserSalt()));
			userService.updateUserInfo(user);
			session.removeAttribute("user");
			session.removeAttribute("verifyCode");
			return "success";
		}else{
			return "fail";
		}
	}
	@RequestMapping("findAllUser")
	@ResponseBody
	public JSONObject findAllUser(Integer page,Integer limit,String keyword) throws UnsupportedEncodingException{
		if(StringUtils.isNoneBlank(keyword)) {
			keyword = URLDecoder.decode(URLEncoder.encode(keyword,"iso8859-1"),"utf-8");
			System.out.println(keyword);
		}
		PageInfo<Users> info = userService.findAllUsersBySplitPage(page,limit,keyword);
		JSONObject obj=new JSONObject();
		obj.put("msg", "");
		obj.put("code", 0);
		obj.put("count",info.getTotal());
		obj.put("data", info.getList());
		return obj;
	}
	@RequestMapping("changeUserState")
	@ResponseBody
	public String changeUserState(Integer userId,Integer state){
		Integer rs = userService.changeUserState(state, userId);
		if(rs>0){
			return "success";
		}else{
			return "fail";
		}
	}
	@RequestMapping("updateUser")
	@ResponseBody
	public String updateUser(Users user){
		Integer rs = userService.updateUserInfo(user);
		if(rs>0){
			return "success";
		}else{
			return "fail";
		}
	}
	@RequestMapping("deleteUser")
	@ResponseBody
	public String deleteUser(Integer userId){
		Integer rs = userService.deleteUser(userId);
		if(rs>0){
			return "success";
		}else{
			return "fail";
		}
	}
	@RequestMapping("batchDelete")
	@ResponseBody
	public String batchDelete(String batchId){
		String[] list = batchId.split(",");
		boolean flag=true;
		for (String id : list) {
			Integer userId = Integer.valueOf(id);
			Integer rs = userService.deleteUser(userId);
			if(rs<0){
				flag=false;
			}
		}
		if(flag){
			return "success";
		}else{
			return "fail";
		}
	}
	@RequestMapping("register")
	@ResponseBody
	public String register(HttpServletRequest request, Users user){//表单序列化后传到这里变成Users对象
		JSONObject json = (JSONObject)request.getSession().getAttribute("verifyCode");
        if(json == null){//对比发出去的验证码和传回来的验证码
			return "fail";
		}
        if(!json.getString("mobile").equals(user.getUserPhone())){
        	return "pfail";
		}
        if(!json.getString("verifyCode").equals(user.getVerifyCode())){
        	return "vfail";
        }
        if((System.currentTimeMillis() - json.getLong("createTime")) > 1000 * 60 * 5){
        	return "tfail";
        }
		user.setUserSalt(RandomStringUtils.randomAscii(12));
		user.setUserPass(MD5Utils.passToMD5(user.getUserPass()+user.getUserSalt()));
		Integer rs = userService.addUser(user);
		request.getSession().removeAttribute("verifyCode");
		if(rs>0){
			return "success";
		}else{
			return "fail";
		}
	}
	@RequestMapping("sendVCode")
	@ResponseBody
	public String sendVCode(HttpServletRequest request, Users user) {//mobile是手机号
		try {
			HttpSession session = request.getSession();
			if(((Users) session.getAttribute("user"))!=null) {
				System.out.println("user已登录");
				user = (Users) session.getAttribute("user");
			}else {
				System.out.println("user未登录");
				if(user.getUserPhone()==null) {
					user.setUserPhone(user.getUserName());
				}
			}
			String mobile = user.getUserPhone();
			//System.out.println(user.getVerifyCode());
			System.out.println(mobile);
			ZhenziSmsClient client = new ZhenziSmsClient("https://sms_developer.zhenzikj.com", "106638", "efd8bd0f-ea8e-4c91-b400-cf1dd728f566");
			//生成6位验证码
            String verifyCode = java.lang.String.valueOf(new Random().nextInt(899999) + 100000);
            //短信内容
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("number", mobile);
            params.put("templateId", "1548");
            String[] templateParams = new String[2];
            templateParams[0] = verifyCode;
            templateParams[1] = "5分钟";
            params.put("templateParams", templateParams);
            JSONObject json = JSONObject.parseObject(client.send(params));
            System.out.println(json.getIntValue("code") + json.getString("data"));
            if(json.getIntValue("code") != 0)//发送短信失败
                return "fail";
            //将验证码存到session中,同时存入创建时间
            //以json存放，这里使用的是阿里的fastjson
            json = new JSONObject();
            json.put("mobile", mobile);
            json.put("verifyCode", verifyCode);
            json.put("createTime", System.currentTimeMillis());
            // 将认证码存入SESSION
            request.getSession().setAttribute("verifyCode", json);
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
	}
}
